/**
 * 路由导航装饰器 实现导航首卫
 */
import store from '@/store'

// 默认装饰的路由名称
const navigationDefaultPatch = ['navigateTo', 'redirectTo', 'switchTab']

const navigationDecorator = (navigationPatch = navigationDefaultPatch) => {
	navigationPatch.forEach(item => {
		const original = uni[item]

		uni[item] = function(options = {}, needAuth = true) {
			// 判断是否有 token
			if (store.getters.token) {
				// 已登录情况下不让进入登陆页
				if (options.url === '/pages/login/index') {
					return false
				}
				return original.call(this, options)
			} else {
				// 没有token 且即将进入的页面需要权限 则跳到登录页
				if (needAuth) {
					uni.navigateTo({
						url: '/pages/login/index'
					}, false)
				} else {
					return original.call(this, options)
				}
			}
		}
	})
}

export default navigationDecorator
